Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

  1. [
  2. [ 1, 2, 3 ],
  3. [ 4, 5, 6 ],
  4. [ 7, 8, 9 ]
  5. ]

You should return [1,2,3,6,9,8,7,4,5].

Solution:

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> res = new ArrayList<Integer>();
  4. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  5. return res;
  6. }
  7. int m = matrix.length;
  8. int n = matrix[0].length;
  9. int layers = (int)Math.ceil(Math.min(m, n) / 2.0);
  10. for (int k = 0; k < layers; k++) {
  11. if (m <= 0 || n <= 0) {
  12. break;
  13. }
  14. // one row
  15. if (m == 1) {
  16. for (int j = 0; j < n; j++) {
  17. res.add(matrix[k][k + j]);
  18. }
  19. }
  20. // one column
  21. else if (n == 1) {
  22. for (int i = 0; i < m; i++) {
  23. res.add(matrix[k + i][k]);
  24. }
  25. }
  26. else {
  27. // top
  28. for (int j = 0; j < n - 1; j++) {
  29. res.add(matrix[k][k + j]);
  30. }
  31. // right
  32. for (int i = 0; i < m - 1; i++) {
  33. res.add(matrix[k + i][k + n - 1]);
  34. }
  35. // bottom
  36. for (int j = n - 1; j > 0; j--) {
  37. res.add(matrix[k + m - 1][k + j]);
  38. }
  39. // left
  40. for (int i = m - 1; i > 0; i--) {
  41. res.add(matrix[k + i][k]);
  42. }
  43. }
  44. m -= 2;
  45. n -= 2;
  46. }
  47. return res;
  48. }
  49. }